<?php

namespace app\index\controller;

use app\common\controller\Frontend;

class Index extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';


    public function index(){
        return $this->view->fetch();
    }


    public function down(){




        //文件夹目录
        $dirPath=ROOT_PATH.'public/uploads/2024';

        //zip压缩包保存路径
        $zipPath= ROOT_PATH."public/uploads/demo.zip";

        try {
            //创建zip实例
            $zip=new \ZipArchive();
            if($zip->open($zipPath, \ZipArchive::CREATE|\ZipArchive::OVERWRITE)=== TRUE) {
                //调用方法，对要打包的根目录进行操作，并将ZipArchive的对象传递给方法
               $this->addFileToZip($zip,$dirPath,$dirPath);
                //关闭处理的zip文件
                $zip->close();
            }

        }catch (\Exception $e) {
            echo '压缩失败';
        }


        $file_path = $zipPath; // 替换为要下载的文件的路径

        if (file_exists($file_path)) {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="' . basename($file_path) . '"');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($file_path));
            readfile($file_path);
            exit;
        } else {
            echo '文件不存在或无法访问。';
        }







//        return $this->view->fetch();
    }


   public function addFileToZip($zip,$path,$root){
        $handler=opendir($path); //打开当前文件夹
        while(($filename=readdir($handler))!==false){
            if($filename != "." && $filename != ".."){//不操作名字为'.'和'..'的文件夹或文件
                if(is_dir($path."/".$filename)){

                    // 如果读取的某个对象是文件夹，则递归

                    addFileToZip($zip,$path."/".$filename,$root);
                }else{
                    //将文件加入zip对象，第二个参数是zip里文件的路径
                    $pathFilename=$path . "/" . $filename;
                    $zip->addFile($pathFilename, str_replace($root.'/','',$pathFilename));
                }
            }
        }
        @closedir($path);
    }



}
